package com.example.api.serveice;

import com.example.api.converter.UserConverter;
import com.example.api.dto.UserDTO;
import com.example.api.entity.User;
import com.example.api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserServiceimp implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public List<UserDTO> getUserAll() {
        List<User> users = userRepository.findAll(); // 获取所有用户实体
        return users.stream()
                .map(UserConverter::convertUserToUserDTO) // 转换为 DTO
                .toList(); // 返回 List<UserDTO>
    }

    @Override
    public User addUser(User user) {
        // 检查邮箱是否已经存在
        List<User> userList = userRepository.findByEmail(user.getEmail());
        if (!CollectionUtils.isEmpty(userList)) {
            throw new RuntimeException("邮箱被占用");
        }


        // 保存用户到数据库
        User savedUser = userRepository.save(user);

        // 转换保存后的 User 为 UserDTO 并返回
        return savedUser;
    }



}
